package cn.com.demo.dao.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import cn.com.common.dao.hibernate.BaseHibernateDao;
import cn.com.demo.dao.TsTourGuideDao;
import cn.com.demo.pojo.TsTourGuide;
@Repository("TsTourGuideDao")
public class TsTourGuideHibernate4DaoImpl extends BaseHibernateDao<TsTourGuide, Integer> implements TsTourGuideDao {

	private static final String HQL_LIST = "from TsTourGuide ";
	private static final String HQL_COUNT = "select count(*) from TsTourGuide ";

	private static final String HQL_LIST_QUERY_CONDITION = " where username like ?";
	private static final String HQL_LIST_QUERY_ALL = HQL_LIST
			+ HQL_LIST_QUERY_CONDITION + "order by id desc";
	private static final String HQL_COUNT_QUERY_ALL = HQL_COUNT
			+ HQL_LIST_QUERY_CONDITION;

	@Override
	public List<TsTourGuide> query(int pn, int pageSize, TsTourGuide command) {
		return list(HQL_LIST_QUERY_ALL, pn, pageSize, getQueryParam(command));
	}

	@Override
	public int countQuery(TsTourGuide command) {
		return this.<Number> aggregate(HQL_COUNT_QUERY_ALL,
				getQueryParam(command)).intValue();
	}

	private Object[] getQueryParam(TsTourGuide command) {
		// TODO 改成全文索引
		String usernameLikeStr = "%" + command.getDyxm() + "%";
		return new Object[] { usernameLikeStr };
	}

	@Override
	public TsTourGuide checkGuidePassword(String userKey, String password) {
		try {
			Session session = this.getSession();
			String hql = "from TsTourGuide as model where model.dysfz =:userKey and  (model.dyzhenghao=:password or model.dyzgzh=:password2 )";
			Query query = session.createQuery(hql);
			query.setString("userKey", userKey);
			query.setString("password", password);
			query.setString("password2", password);
			List<TsTourGuide> list = query.list();
			if (null != list && list.size() > 0) {
				return list.get(0);
			}
		} catch (RuntimeException re) {
			throw re;
		}
		return null;
	}

	@Override
	public List<TsTourGuide> findByProperty(String propertyName, Object value) {
		try {
			String queryString = "from TsTourGuide as model where model."
					+ propertyName + "= ?";
			return this.findByProperty(queryString, value);
		} catch (RuntimeException re) {
			throw re;
		}
	}
}
